import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
 * <p>
 * 示例 1:
 * <p>
 * 输入:
 * [
 * [ 1, 2, 3 ],
 * [ 4, 5, 6 ],
 * [ 7, 8, 9 ]
 * ]
 * 输出: [1,2,3,6,9,8,7,4,5]
 */
class Solution {

    public static void main(String[] args) {
        int[][] matrix = new int[3][4];
        int[] a1 = new int[]{1, 2, 3, 4};
        int[] a2 = new int[]{5, 6, 7, 8};
        int[] a3 = new int[]{9, 10, 11, 12};
        matrix[0] = a1;
        matrix[1] = a2;
        matrix[2] = a3;
        Solution solution=new Solution();
        List<Integer> list = solution.spiralOrder(matrix);
        for (Integer integer : list) {
            System.out.print(integer + ",");
        }
        System.out.println("");
    }

    private List<Integer> list = new ArrayList<Integer>();

    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length==0||matrix[0].length==0) {
            return list;
        }
        // l1表示一行几个
        int x = matrix[0].length;
        // l2表示一共几列
        int y = matrix.length;
        circle(matrix, x, y, 0);
        return list;
    }

    public void circle(int[][] matrix, int x, int y, int n) {
        int now = n << 1;
        int x1 = x - now;
        int y1 = y - now;
        if (x1 <= 0 || y1 <= 0) {
        } else if (y1 == 1) {
            int s = x - n;
            for (int i = n; i < s; i++) {
                list.add(matrix[n][i]);
            }
        } else if (x1 == 1) {
            int s = y - n;
            for (int i = n; i < s; i++) {
                list.add(matrix[i][n]);
            }
        } else {
            int s1 = x - 1 - n;
            int s2 = y - 1 - n;
            for (int i = n; i <= s1; i++) {
                list.add(matrix[n][i]);
            }
            for (int i = n + 1; i <= s2; i++) {
                list.add(matrix[i][s1]);
            }
            for (int i = s1 - 1; i >= n; i--) {
                list.add(matrix[s2][i]);
            }
            for (int i = s2 - 1; i >= n + 1; i--) {
                list.add(matrix[i][n]);
            }
            circle(matrix, x, y, n + 1);
        }
    }


}